import { createRouter, createWebHashHistory } from "vue-router";
// 引入路由文件
import Layout from "@/views/layout/index.vue";
// import { login } from "../api/user.js";

export const routes = [
  {
    path: "/login",
    name: "login",
    label: "登录",
    hidden: true,
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/",
    label: "首页",
    component: Layout,
  },
  {
    path: "/banner",
    label: "轮播图管理",
    component: Layout,
    children: [
      {
        path: "list",
        // 路由懒加载
        label: "轮播图列表",
        component: () => import("@/views/banner/list.vue"),
      },
      {
        path: "add",
        label: "轮播图新增",
        component: () => import("@/views/banner/add.vue"),
      },
    ],
  },
  {
    path: "/manager",
    label: "管理员管理",
    component: Layout,
    children: [
      {
        path: "list",
        label: "管理员列表",
        component: () => import("@/views/manager/list.vue"),
      },
    ],
  },
];
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URLs),
  routes,
});

// 定义一个数组，数组中每一项是一个路由的 name 的值， 配置在这个数组中的路由name，代表不需要检验登录
const whiteList = ["login"];
// 全局前置守卫
router.beforeEach((to, form, next) => {
  const name = to.name;

  if (whiteList.includes(name)) {
    // 存在，说明这个to不需要校验登录，直接放行
    next();
  } else {
    // 不存在,需要校验登录状态
    const token = localStorage.getItem("token");
    if (token) {
      // 登录了，直接放行
      next();
    } else {
      // 没登录，需要重定向到登录页面
      next({ name: "login" });
    }
  }
});
export default router;

/**
 * 1. /login    views/Login.vue
 * 2. /         views/Layout.vue
 *      1. /banner/list     views/banner/list.vue
 *      2. /banner/add      views/banner/add.vue
 *
 *      3. /manager/list    views/manager/list.vue
 *
 */
